// 模拟接口：遗嘱下达设置相关
// 说明：真实环境应替换为后端API，这里仅用于演示与页面联调

// 内部内存数据（模拟数据库）
let _autoId = 1000
let _issueRules = [
  {
    id: 1,
    drugType: '医疗器械',
    tcmProcess: '',
    sourceDept: '全部科室',
    ward: '全部病区',
    deliverTo: '本地药房',
    enabled: true,
    isDefault: true
  },
  {
    id: 2,
    drugType: '西药',
    tcmProcess: '',
    sourceDept: '全部科室',
    ward: '全部病区',
    deliverTo: '本地药房',
    enabled: true,
    isDefault: false
  },
  {
    id: 3,
    drugType: '中成药',
    tcmProcess: '',
    sourceDept: '全部科室',
    ward: '全部病区',
    deliverTo: '本地药房',
    enabled: true,
    isDefault: false
  },
  {
    id: 4,
    drugType: '中药饮片',
    tcmProcess: '先煎',
    sourceDept: '全部科室',
    ward: '全部病区',
    deliverTo: '本地药房',
    enabled: true,
    isDefault: false
  },
  {
    id: 5,
    drugType: '中药颗粒',
    tcmProcess: '后下',
    sourceDept: '全部科室',
    ward: '全部病区',
    deliverTo: '本地药房',
    enabled: true,
    isDefault: false
  }
]

let _prescribeSettings = {
  insufficientStockBehavior: 'allow_hint',
  expiredDrugBehavior: 'no_hint',
  outpatientLock: 'after_order',
  inpatientLock: 'after_verify'
}

export const mockOrderIssueApi = {
  // 获取下达规则列表
  getIssueRuleList({ pageNum = 1, pageSize = 10 } = {}) {
    const start = (pageNum - 1) * pageSize
    const end = start + pageSize
    const list = _issueRules.slice(start, end)
    return {
      code: 200,
      data: {
        list,
        total: _issueRules.length
      }
    }
  },

  // 新增下达规则
  addIssueRule(payload) {
    const id = ++_autoId
    const record = {
      id,
      drugType: payload.drugType || '未知',
      tcmProcess: payload.tcmProcess || '',
      sourceDept: (payload.sourceDepts && payload.sourceDepts.join('、')) || '全部科室',
      ward: (payload.wards && payload.wards.join('、')) || '全部病区',
      deliverTo: payload.deliverTo || '本地药房',
      enabled: true,
      isDefault: false
    }
    _issueRules.unshift(record)
    return { code: 200, message: '新增成功', data: record }
  },

  // 删除规则
  deleteIssueRule(id) {
    _issueRules = _issueRules.filter(item => item.id !== id)
    return { code: 200, message: '删除成功' }
  },

  // 切换启用状态
  toggleRuleStatus(id) {
    const target = _issueRules.find(item => item.id === id)
    if (!target) return { code: 404, message: '规则不存在' }
    // 非默认规则可以切换，默认规则始终启用
    if (!target.isDefault) {
      target.enabled = !target.enabled
    }
    return { code: 200, message: '状态已更新', data: target }
  },

  // 保存“开出规则设置”
  savePrescribeSettings(payload) {
    _prescribeSettings = { ..._prescribeSettings, ...payload }
    return { code: 200, message: '设置保存成功', data: _prescribeSettings }
  },

  // 读取“开出规则设置”
  getPrescribeSettings() {
    return { code: 200, data: _prescribeSettings }
  }
}

export default mockOrderIssueApi
